const BookInstance = require('../models/bookinstance');
const Book = require('../models/book');
const async = require('async');
const {body,validationResult} = require('express-validator/check');
const {sanitizeBody} = require('express-validator/filter');

exports.book_instance_list = (req,res,next)=>{
    BookInstance.find().populate('book').exec(function (err, list_book_instance) {
        if(err){
            next(err);
        }else{
            //console.log({list_book_instance})
            res.render('book_instance_list',{title:'Book Instance List',list:list_book_instance});
        }
    })
};

exports.book_instance_detail = (req,res,next)=>{
    BookInstance.findById(req.params.id).populate('book')
        .exec(function (err, bookInstance) {
            if(err){
                next(err);
            }else{
                if(bookInstance==null){
                    err = new Error('book instance not found')
                    err.statusCode = 404;
                    next(err);
                }else{
                    res.render('book_instance_detail',{
                        title:'当前书本',
                        bookInstance
                    })
                }
            }
        })
};

exports.book_instance_create_get = (req,res,next)=>{
    Book.find(function (err, books) {
        if(err) return next(err);
        res.render('book_instance_form',{title:'创建图书实例',books})
    })
};
exports.book_instance_create_post = [
    body('book','book is required').isLength({min:1}).trim(),
    body('imprint','imprint is required').isLength({min:1}).trim(),
    body('due_back','日期格式不合法').optional({checkFalsy:true}).isISO8601(),
    sanitizeBody('book').escape(),
    sanitizeBody('status').trim().escape(),
    sanitizeBody('due_back').toDate(),
    sanitizeBody('imprint').escape(),
    (req,res,next)=>{
        const errors = validationResult(req);
        let book_instance = new BookInstance({
            ...req.body
        });
        if(!errors.isEmpty()){
            Book.find(function (err, books) {
                if(err) return next(err);
                res.render('book_instance_form',{'title':'重新添加实例',books,book_instance,errors:errors.array()})
            })
        }else{
            book_instance.save(function (err) {
                if(err) return next(err);
                res.redirect(book_instance.url);
            })
        }
    }
];

exports.book_instance_delete_post = (req,res)=>{
    const id = req.params.id;
    BookInstance.findByIdAndRemove(id,function (err) {
        if(err) return next(err);
        res.redirect('/catalog/book_instances');
    });
};
exports.book_instance_update_get = (req,res,next)=>{
    async.parallel({
        books:function (cb) {
            Book.find(cb);
        },
        book_instance:function (cb) {
            BookInstance.findById(req.params.id).exec(cb);
        }
    },function (err, results) {
        if(err) return next(err);
        res.render('book_instance_update',{title:'编辑图书实例',books:results.books,book_instance:results.book_instance});
    });
};
exports.book_instance_update_post =  [
    body('book','book is required').isLength({min:1}).trim(),
    body('imprint','imprint is required').isLength({min:1}).trim(),
    body('due_back','日期格式不合法').optional({checkFalsy:true}).isISO8601(),
    sanitizeBody('book').escape(),
    sanitizeBody('status').trim().escape(),
    sanitizeBody('due_back').toDate(),
    sanitizeBody('imprint').escape(),
    (req,res,next)=>{
        const errors = validationResult(req);
        let book_instance = new BookInstance({
            ...req.body,
            _id:req.params.id
        });
        if(!errors.isEmpty()){
            Book.find(function (err, books) {
                if(err) return next(err);
                res.render('book_instance_form',{'title':'重新更新实例',books,book_instance,errors:errors.array()})
            })
        }else{
            BookInstance.findByIdAndUpdate(req.params.id,book_instance,{},function (err,theInstance) {
                if(err) return next(err);
                res.redirect(theInstance.url);
            })
        }
    }
];
